package com.lcredu.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 黎长容
 * @date 2025-07-27 17:46
 */
public class MybatisUtils {
    //返回一个sqlSession
    private static SqlSessionFactory sqlSessionFactory;

    static {
        //使用 mybatis 第一步：获取 sqlSessionFactory 对象
        String resource = "mybatis-config.xml";
        try {
            InputStream resourceAsStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 1. 返回一个SqlSession
     * 2. SqlSession 提供了对数据库执行 SQL 命令所需的所有方法
     * 3. 通过 SqlSession 实例来直接执行已映射的 SQL 语句
     *
     * @return
     */
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}
